﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace daemon
{
    public partial class FrmUpgradeProgresscs : Form
    {
        private Dictionary<string, object> _args;
        public FrmUpgradeProgresscs(Dictionary<string, object> args)
        {
            InitializeComponent();
            _args = args;
        }

        private void SetProgress(int total, int current)
        {
            this.Invoke(new Action(() =>
            {
                progressBar1.Maximum = total;
                progressBar1.Value = current;
                var percent = Convert.ToInt32(current * 100m / total);
                label1.Text = $"正在升级软件包{percent}%({current}/{total})...";
            }));
        }

        private void Start()
        {
            var list = Helper.ToStringOrEmpty(_args["list"]);
            var packages = list.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            for (var index = 0; index < packages.Length; index++)
            {
                var item = packages[index];
                string[] items = item.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                string packageName = items[0];
                string version = items[1];
                //OnMessage($"正在应用更新包{version}...");
                SetProgress(packages.Length, index + 1);
                UpgradePackage(packageName, version);
            }
        }

        private void UpgradePackage(string packageName, string version)
        {
            try
            {
                packageName = packageName.Trim();
                var baseDir = AppDomain.CurrentDomain.BaseDirectory;
                //OnMessage($"更新版本{version}:正在解压更新文件...");
                var extractDir = Path.Combine(baseDir, Guid.NewGuid().ToString("N"));
                Directory.CreateDirectory(extractDir);
                var packagePath = Path.Combine(baseDir, packageName);
                System.IO.Compression.ZipFile.ExtractToDirectory(packagePath, extractDir);

                //OnMessage($"更新版本{version}:正在应用更新...");
                //string versionBackupDir = Path.Combine(baseDir, "Backup", $"Version{version}");
                //if (Directory.Exists(versionBackupDir))
                //{
                //    Directory.Delete(versionBackupDir, true);
                //}

                ReplaceFile(extractDir, baseDir);
                //OnMessage($"更新版本{version}:正在删除临时文件...");
                File.Delete(packagePath);
                Directory.Delete(extractDir, true);
                var versionPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "version.ini");
                File.WriteAllText(versionPath, version, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 替换文件
        /// </summary>
        /// <param name="targetDir">目标目录</param>
        /// <param name="currentDir">当前目录</param>
        private void ReplaceFile(string targetDir, string currentDir)
        {
            var files = Directory.GetFiles(targetDir);
            foreach (string file in files)
            {
                string fileName = Path.GetFileName(file);
                if (string.IsNullOrEmpty(fileName)) continue;
                //if (fileName.Equals("LocalVersion.json", StringComparison.OrdinalIgnoreCase)) continue;//本地版本配置文件不覆盖
                if (!Directory.Exists(currentDir))
                {
                    Directory.CreateDirectory(currentDir);
                }

                string sourceFilePath = Path.Combine(currentDir, fileName);
                //if (File.Exists(sourceFilePath))
                //{
                //    Directory.CreateDirectory(backupDir);
                //    File.Move(sourceFilePath, Path.Combine(backupDir, fileName));
                //}

                File.Copy(file, sourceFilePath, true);
            }

            foreach (string dir in Directory.GetDirectories(targetDir))
            {
                string dirName = Path.GetFileName(dir);
                if (string.IsNullOrEmpty(dirName)) continue;
                //string subDir = Path.Combine(backupDir, dirName);
                ReplaceFile(dir, Path.Combine(currentDir, dirName));
            }
        }

        private async void FrmUpgradeProgresscs_Load(object sender, EventArgs e)
        {
            await Task.Factory.StartNew(Start);
            var path = Helper.ToStringOrEmpty(_args["path"]);
            Helper.StartupByPath(path); //启动文件路径
            System.Environment.Exit(0);
        }

        private void FrmUpgradeProgresscs_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
        }
    }
}
